<template>
  <el-card class="page-tools">
    <el-row type="flex" justify="space-between" align="middle">
      <!-- 左边添加页面 -->
      <el-col>
        <el-button
          type="primary"
          @click="addFn"
        >添加页面</el-button>

        <el-dialog
          :title="pageForm.id?'编辑页面':'添加页面'"
          :visible="isShowDialog"
          @close="cancelFn"
        >
          <el-form ref="pageForm" :model="pageForm" label-width="120px" :rules="rules">
            <el-form-item label="标题" prop="title">
              <el-input v-model="pageForm.title" placeholder="请输入标题" />
            </el-form-item>
            <!-- <el-form-item label="内容" :label-width="formLabelWidth" /> -->

            <!-- 富文本框 -->
            <el-form-item label="内容" prop="content">
              <VueEditor ref="vueEditor" :config="config" />
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="cancelFn">取 消</el-button>
            <el-button type="primary" @click="confirmFn">确 定</el-button>
          </div>
        </el-dialog>

      </el-col>

      <!-- 右边搜索框和筛选按钮 -->
      <el-col class="myInput">
        <el-dropdown disabled="true" placement="bottom-start" trigger="click" @command="ChangeValue" @click.native="isShowDropdown">
          <el-input ref="seachInput" v-model.trim="title_contains" style="width:600px" type="" size="small" placeholder="请输入关键字" class="input-with-select">
            <el-button slot="append" type="small" @click="editPages">筛选</el-button>
            <el-dropdown-menu v-show="isDropdown" slot="dropdown">
              <el-dropdown-item v-if="myHistory.length===0" disabled>没有历史记录</el-dropdown-item>
              <el-dropdown-item v-for="item,index in myHistory" :key="index" :command="item">{{ item }}</el-dropdown-item>
            </el-dropdown-menu>
          </el-input></el-dropdown>
      </el-col>
    </el-row>
    <!-- 分割线 -->
    <el-divider />

    <!-- 表格 -->
    <el-table
      :data="pagesList"
      border
      style="width: 100%"
      align="center"
    >
      <!-- 标题 -->
      <el-table-column
        prop="title"
        label="标题"
      />
      <!-- 内容 -->
      <el-table-column
        prop="content"
        label="内容"
      >
        <template v-slot="{row}">
          <div v-html="row.content" />
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
      >
        <template v-slot="{row}">
          <el-button type="primary" @click="editor(row.id)">编辑</el-button>
          <el-button type="danger" @click="delPages(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分割线 -->
    <el-divider />

    <!-- 分页 -->
    <div class="block" align="middle">
      <el-pagination
        layout="prev, pager, next"
        :total="total"
        :page-size="page._limit"
        @prev-click="prevClick"
        @next-click="nextClick"
        @current-change="currentChangeFn"
      />
    </div>
  </el-card>
</template>

<script>
import VueEditor from 'vue-word-editor'
import 'quill/dist/quill.snow.css'
import { getPagesList, getPagesNum, delPages, addPagesNum, undatePages, getPageInfo } from '@/api/page'
export default {
  components: { VueEditor },
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === '<p><br></p >') {
        callback(new Error('请输入内容'))
      }
      if (this.$refs.vueEditor.editor.getLength() === 1) {
        callback(new Error('请输入内容'))
      }
      callback()
    }
    return {
      input: '',
      pagesList: [],
      page: {
        _limit: 5, // 获取多少条
        _start: 0, // 多少条开始
        title_contains: ''// 模糊查询的标题
      },
      title_contains: '',
      total: 0, // 多少条数据
      currentPage: 1, // 当前页
      isShowDialog: false,
      isDropdown: true, // 控制搜索显示
      myHistory: JSON.parse(localStorage.getItem('myHistory')) || [], // 历史记录
      // 弹出框
      pageForm: {
        title: '',
        content: ''
      },
      formLabelWidth: '120px',
      config: {
        // 上传文本的配置
        uploadImage: {
          url: 'http://localhost:9529/upload', // 文章上传到服务器端的处理路径
          name: 'file', // 后台所需要的参数的名称
          // res是结果，insert方法会把内容注入到编辑器中，res.data.url是资源地址
          uploadSuccess(res, insert) {
            insert('http://localhost:9529' + res.data.url)// 文件上传之后的回调，接收服务器响应回来的数据，根据服务器的地址进行填充
          }
        }
      },
      rules: {
        title: [
          { required: true, message: '标题不能为空', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '内容不能为空', trigger: 'blur' },
          { validator: validatePass, trigger: 'change' }
        ]
      }
    }
  },
  async created() {
    // 获取页面列表
    await this.getPagesList()
    // 获取页面数量
    await this.getPagesNum()
  },
  methods: {
    // 取消关闭弹窗
    cancelFn() {
      this.isShowDialog = false
      this.pageForm = {
        title: '',
        content: ''
      }
    },
    // 添加
    addFn() {
      this.isShowDialog = true
    },
    // 编辑
    async editor(id) {
      this.isShowDialog = true
      const res = await getPageInfo(id)
      this.pageForm = res
      // console.log(175, res)
      // console.log(175, res.data)
      this.$refs.vueEditor.editor.root.innerHTML = this.pageForm.content
    },
    // 获取页面列表
    async getPagesList() {
      const res = await getPagesList(this.page)
      this.pagesList = res
      // console.log(1, res)
    },
    // 上一页
    prevClick() {
      this.page._start -= 5
      this.getPagesList()
    },
    // 下一页
    nextClick() {
      this.page._start += 5
      this.getPagesList()
    },
    // 获取页面数量
    async getPagesNum() {
      const res = await getPagesNum({ title_contains: this.page.title_contains })
      this.total = res
      // console.log(2, res)
    },
    // 点击页码跳转
    currentChangeFn(newpage) {
      // console.log(3, newpage)
      this.page._start = (newpage - 1) * this.page._limit
      this.getPagesList()
    },
    // 删除功能
    async delPages(id) {
      console.log(id)
      // 确认删除功能
      this.$confirm('确定要删除麽?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        // 点击了确认按钮 触发then函数
        // 调用删除接口函数
        await delPages(id)
        // 更新浏览器中显示的数据
        await this.getPagesList()
        // 获取页面数量
        await this.getPagesNum()
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        // 点击取消按钮  触发catch函数
        this.$message.warning('取消删除成功!')
      })
    },
    // 点击筛选框
    async  editPages() {
      // await getPagesList({ title_contains:input })
      this.page.title_contains = this.title_contains
      const flag = this.myHistory.includes(this.title_contains)
      if (this.title_contains && !flag) {
        this.myHistory.push(this.title_contains)
      }
      localStorage.setItem('myHistory', JSON.stringify(this.myHistory))
      // 获取页面列表
      await this.getPagesList()
      // 获取页面列表数
      await this.getPagesNum()
    },
    // 判断是否隐藏
    isShowDropdown(e) {
      const flag = e.target.classList.contains('el-input__inner')
      console.log(flag)
      if (flag) {
        this.isDropdown = true
      } else {
        this.isDropdown = false
      }
    },
    // 给输入框赋值历史记录
    async  ChangeValue(val) {
      this.title_contains = this.page.title_contains = val
      // 获取经纪列表
      await this.getPagesList()
      // 获取经纪数
      await this.getPagesNum()
    },
    async confirmFn() {
      // 获取富文本的内容
      // this.form.content = this.$refs.vueEditor.editor.root.innerHTML
      try {
        this.pageForm.content = this.$refs.vueEditor.editor.root.innerHTML
        await this.$refs.pageForm.validate()
        if (this.pageForm.id) {
          await undatePages(this.pageForm)
          this.$message.success('编辑成功')
        } else {
          await addPagesNum(this.pageForm)
          this.$message.success('添加成功')
        }
        this.getPagesList()
        this.cancelFn()
      } catch (err) {
        console.log(err)
      }
    }
    //
  }
}

</script>
<style lang='scss'>
 .page-tools {
    margin: 10px 0;
    .before {
      line-height: 34px;
    i {
      margin-right: 5px;
      color: #409eff;
    }
    display: inline-block;
    padding: 0px 10px;
    border-radius: 3px;
    border: 1px solid rgba(145, 213, 255, 1);
    background: rgba(230, 247, 255, 1);
  }
  .el-table{
  margin-top:20px ;
}
::v-deep .el-dropdown-menu{
  left: 740px !important
}
.myInput{
display: flex;
justify-content: end;
}
 }
</style>
